<script setup lang="ts">
import { ref } from 'vue'

const expr = ref('')
const lastAnswer = ref<number | null>(null)

function insert(token: string) {
  expr.value += token
}

function clearAll() {
  expr.value = ''
}

function backspace() {
  expr.value = expr.value.slice(0, -1)
}

function useAns() {
  if (lastAnswer.value !== null) expr.value += String(lastAnswer.value)
}

function transformExpression(raw: string) {
  let s = raw
  s = s.replace(/\^/g, '**')
  s = s.replace(/sin\(/g, 'Math.sin(')
  s = s.replace(/cos\(/g, 'Math.cos(')
  s = s.replace(/tan\(/g, 'Math.tan(')
  s = s.replace(/sqrt\(/g, 'Math.sqrt(')
  s = s.replace(/log\(/g, 'Math.log(')
  return s
}

function evaluate() {
  try {
    const transformed = transformExpression(expr.value)
    // 限制可执行的字符集，基础安全防护
    if (/[^0-9+\-*/().^\sA-Za-z]/.test(expr.value)) throw new Error('包含非法字符')
    const fn = new Function('return ' + transformed)
    const res = fn()
    if (typeof res !== 'number' || Number.isNaN(res)) throw new Error('表达式无效')
    lastAnswer.value = res
    expr.value = String(res)
  } catch (e: any) {
    alert('计算错误：' + (e?.message || '未知错误'))
  }
}

const keys = [
  ['sin(', 'cos(', 'tan(', 'sqrt('],
  ['7', '8', '9', '/'],
  ['4', '5', '6', '*'],
  ['1', '2', '3', '-'],
  ['0', '.', '^', '+'],
]
</script>

<template>
  <div class="space-y-4">
    <div class="flex items-center gap-2">
      <input
        v-model="expr"
        placeholder="输入表达式，如: sqrt(2^2 + 3^2)"
        class="flex-1 p-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-primary/50"
      />
      <button class="px-3 py-2 bg-secondary text-white rounded hover:bg-secondary/90" @click="evaluate">=
      </button>
    </div>
    <div class="grid grid-cols-4 gap-2">
      <button
        v-for="row in keys"
        :key="row.join('-')"
        class="contents"
      >
        <button
          v-for="k in row"
          :key="k"
          class="px-3 py-2 bg-gray-200 dark:bg-gray-700 rounded hover:bg-gray-300 dark:hover:bg-gray-600"
          @click="insert(k)"
        >
          {{ k }}
        </button>
      </button>
      <button class="px-3 py-2 bg-accent text-white rounded hover:bg-accent/90" @click="useAns">Ans</button>
      <button class="px-3 py-2 bg-gray-500 text-white rounded hover:bg-gray-600" @click="backspace">DEL</button>
      <button class="px-3 py-2 bg-primary text-white rounded hover:bg-primary/90 col-span-2" @click="clearAll">AC</button>
    </div>
    <p class="text-sm text-gray-500 dark:text-gray-400">支持: + - * / ^ ( )、sin cos tan sqrt log</p>
  </div>
</template>

<style scoped></style>